﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;

namespace Common.Jwt.Extensions
{
    public class JwtTokenMiddleware
    {
        private readonly RequestDelegate _next;
        public IConfiguration _configuration;
        public JwtTokenMiddleware(RequestDelegate next, IConfiguration configuration)
        {
            _next = next;
            _configuration = configuration;
        }

        public async Task Invoke(HttpContext context)
        {
            //表示如果是获取token则不走ocelot
            var path = context.Request.Path.Value;
            if (context.Request.Method == "GET" && !string.IsNullOrWhiteSpace(path) && path.ToLower() == ("/gateway/GetJwtToken".ToLower()))
            {
                var userName = context.Request.Query["userName"].ToString();
                var userId = context.Request.Query["userId"].ToString();
                var userType = context.Request.Query["userType"].ToString();
                if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(userId))
                {
                    context.Response.StatusCode = 500;//参数错误
                    await context.Response.WriteAsync("参数错误");
                    return;
                }
                var token = JwtHelper.GetJwtToken(new JwtUserModel()
                {
                    UserName = userName,
                    UserId = userId,
                    UserType = userType
                });
                context.Response.StatusCode = 200;
                await context.Response.WriteAsync(token);
                return;
            }
            await _next.Invoke(context);
        }
    }
}
